<?php

namespace app\admin\controller;

use think\Controller;

use think\Db;
use think\Request;

class Links extends Admin
{

    public function __construct(){
        parent::initialize();
        // var_dump($this->initialize()) ;

    }
    public function edit()
    {

      
        $id = input('id');
        $links = db('to_links')->find($id);
        $title = $links['title'];
        $url = $links['url'];
        $desc = $links['desc'];

        return $this->fetch('links/edit', [
            'id' => $id,
            'title' => $title,
            'url' => $url,
            'desc' => $desc

        ]);


    }

    public function edits(){
        $id = input('id');
        // dump($id);die;
        $links = db('to_links')->find($id);

        if (request()->isPost()) {
            $data = [
                'id' => $id,
                'title' => input('title'),
                'url' => input('url'),
                'desc' => input('desc')
            ];
    

            $validate = \think\Loader::validate('Links');
            if (!$validate->check($data)) {
                $this->error($validate->getError());
                die;
            }
            if (db('to_links')->update($data)) {
                $this->success('修改链接成功',url('admin/Links/lst'));

            } else {
                $this->error('修改链接失败');
            }
            return;
        }
    }

    public function add()
    {
        return view('links/add');
    }


    public function lst()
    {
        $list = Db::name('to_links')->field(['id', 'title', 'url', 'desc'])->paginate(3);

        return $this->fetch('links/links',[
            'list' => $list
        ]);
    }

    // 增加链接操作
    public function addLinks()
    {
        if (request()->isPost()) {
            $data = [
                'title' => input('title'),
                'url' => input('url'),
                'desc' => input('desc')
            ];
            $validate = \think\Loader::validate('Links');
            if (!$validate->scene('add')->check($data)) {
                $this->error($validate->getError());
                die;
            };
            if (db('to_links')->insert($data)) {
                return $this->success('添加链接成功', url('admin/Links/lst'));
            } else {
                return $this->error('添加链接失败');
            }
            return;
        }
    }


    // 删除链接
    public function del()
    {
        $id =input('id');


        if (db('to_links')->delete($id)) {

            $this->success('删除链接成功', 'admin/links/lst');
        } else {
            $this->error('删除链接失败');
        }
        return;


        return $this->redirect('admin/links/lst');
    }


}
